// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <string>
#include <string_view>

#include "rapidjson/document.h"
#include <rapidjson/error/en.h>
#include <rapidjson/stringbuffer.h>

#include "coin2/base/time.h"
#include "coin2/exchange/base/feed/latency_extractor.h"

namespace coin2::exchange::okex_common::feed_v3 {
namespace impl {

using coin2::exchange::base::executor::TopicRecordPacket;
using namespace std::string_literals;

class OkexCommonLatencyExtractor : public base::feed::LatencyExtractor {
 public:
  void ExtractLatency(std::shared_ptr<TopicRecordPacket> packet) override {
    if (packet->payload == "pong") {
      return;
    }

    rapidjson::Document document;
    document.Parse(packet->payload.data());
    if (document.HasParseError()) {
      throw std::runtime_error("JSON parse error: "s + GetParseError_En(document.GetParseError()));
    }

    if (!document.HasMember("table") || !document.HasMember("data")) {
      return;
    }

    const auto& data = document["data"].GetArray();
    std::string_view timestamp = data[0]["timestamp"].GetString();

    int64_t et = TimestampFromOkexIso8601(timestamp);
    Update(packet->timestamp, et);
    LogPacket(packet);
  }
};

}  // namespace impl
using impl::OkexCommonLatencyExtractor;
}  // namespace coin2::exchange::okex_common::feed_v3
